import {useReducer, useState} from "react";

function UseReducerPage() {
  /**
   * useState实现
   */
  const [count, setCount] = useState(0);
  const handleAdd = (num: number) => {
    setCount(count + num);
  }

  /**
   * useReducer实现
   */
    // 默认值
  const initialState = {
      number: -1,
      price: 99
    }
  type State = typeof initialState;
  // 初始化函数。只执行一次。可以修饰默认值
  const initFn = (state: State) => {
    console.log('initFn-state:', state);
    // return state;
    // 初始化函数，把负数处理成正数了。
    return {...state, number: Math.abs(state.number)};
  }
  // 处理函数。默认不执行，dispatch后才会触发。
  const reducer = (state: State, action: { type: 'add' | 'sub' }) => {
    console.log('reducer-state:', state, action);
    // return state
    switch (action.type) {
      case 'add':
        return {number: state.number + 1};
      case 'sub':
        return {...state, number: state.number - 1};
      default:
        return state;
    }
  }
  const [userState, dispatch] = useReducer(reducer, initialState, initFn);
  return (
    <div>
      <h2>useState实现</h2>
      <div>count: {count}</div>
      <div>
        <button onClick={() => handleAdd(1)}>+1</button>
        <button onClick={() => handleAdd(-1)}>-1</button>
      </div>
      <hr/>

      <h2>useReducer实现</h2>
      <div>
        数量：{userState.number}，价格：{userState.price}
      </div>
      <div>
        <button onClick={() => dispatch({type: 'add'})}>+1</button>
        <button onClick={() => dispatch({type: 'sub'})}>-1</button>
      </div>
    </div>
  )
}

export default UseReducerPage;
